 <!--
* description: 维修出库
* author: wangjuan
* createdDate: 2021-4-13

* author: chenweilin
* carryDate: 2021/7/12
-->
<template>
  <div class="app-container app-container-table" style="padding:0;">
    <one-table-template
      ref="multipleTable"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-table-cols="tableCols"
      :dynamic-api-config="apiConfig"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="false"
      :dynamic-is-show-more-btn="true"
      :stripe="false"
      :callback-obj="callbackObj"
    >
      <!-- 出库数量-->
      <!--          :max="scope.row['canInStoreQty'] || 1000"-->
      <template #outStoreQty="scope">
        <el-input-number
          :key="'outqty'"
          v-model="scope.row['outStoreQty']"
          :step="1"
          :min="1"
          @change="outStoreQtyChange($event, scope.row, scope.col)"
          step-strictly
        />
      </template>
      <!--      出库仓库-->
      <template #warehouseId="scope">
        <el-select
          v-model="scope.row['warehouseId']"
          placeholder="请选择"
          @visible-change="visChange($event, scope.row, scope.col)"
          @change="valChange($event, scope.row, scope.col)"
        >
          <el-option
            v-for="item in scope.row['options'] || [{
              warehouseId: scope.row.warehouseId,
              warehouseName: scope.row.warehouseName
            }]"
            :key="item.warehouseId"
            :label="item.warehouseName"
            :value="item.warehouseId"
          />
        </el-select>
      </template>
    </one-table-template>
    <edit
      :edit-row-data="editRowData"
      :popupsVisible.sync="visiblePop"
      ref="Edit"
    >
    </edit>
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import api from '@/api/pa/apiBranchWarehouse';
import Vue from 'vue';
// import Edit from './maintenanceDeliveryEdit';

export default {
  name: 'OtherDelivery',

  components: {
    OneTableTemplate,
    Edit: () => import('./maintenanceDeliveryEdit.vue')
  },

  // 组件混入对象：{data[listQuery] methods[queryTable]}
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ''], function() {
      next()
    })
  },

  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])

    return {
      editRowData: {},
      visiblePop: false,
      selectData: {},
      // 网格查询API配置对象
      apiConfig: api.queryRepairOutStorageInfo,

      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.queryTable(1),
          text: this.$t('sys.button.query'), // 查询
          position: 'right',
          fuzzySearch: true
        },
        // {
        //   compKey: 'btnKey2',
        //   size: 'small',
        //   clickEvent: () => this.delivery(),
        //   text: '出库',
        //   position: 'left',
        //   disabled: true
        // },
        {
          compKey: 'btnKey3',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.reset(),
          text: this.$t('sys.button.reset'),
          position: 'right' // 重置
        }
      ],
      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '维修单号：',
              codeField: 'repairOrderCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey2',
              labelName: '车牌号：',
              codeField: 'carLicense',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey3',
              labelName: '客户姓名：',
              codeField: 'custName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey4',
              labelName: '派工日期：',
              codeField: 'beginDate,endDate',
              component: () => import('@/components/org/datePicker/datePicker'),
              dateType: 'daterange',
              isMul: false,
              isMust: true
            },
            // {
            //   compKey: 'compKey5',
            //   labelName: '出库仓库：',
            //   codeField: 'warehouseName',
            //   component: () => import('@/components/org/commonSelect'),
            //   oFields: 'warehouseName,warehouseName',
            //   customObj: {
            //     api: api.queryOutStorage,
            //     listQuery: {
            //       warehouseName: ''
            //     },
            //     selectType: '1'
            //   },
            //   type: 'dropdownList',
            //   isMul: false,
            //   isMust: false
            // },
            // {
            //   compKey: 'compKey6',
            //   labelName: '备件编码：',
            //   codeField: 'partNo',
            //   component: () => import('@/components/org/commonInput'),
            //   type: 'inputText',
            //   isMul: false,
            //   isMust: false
            // },
            // {
            //   compKey: 'compKey7',
            //   labelName: '备件名称：',
            //   codeField: 'partName',
            //   component: () => import('@/components/org/commonInput'),
            //   type: 'inputText',
            //   isMul: false,
            //   isMust: false
            // }
          ],
      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'isRetrospect',
              label: '是否追溯',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'warehouseId',
              label: '仓库ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'dlrId',
              label: '网点Id',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'partId',
              label: '备件Id',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'updateControlId',
              label: '并发控制ID',
              hidden: true,
              alwaysHidden: true
            },
            // {
            //   prop: 'repairOrderCode',
            //   label: '维修单号',
            //   width: 140
            // },
            {
              prop: 'repairOrderCode',
              label: '维修单号',
              isComponent: true,
              width: 140,
              comps: [
                {
                  compKey: 'propKey1',
                  codeField: 'repairOrderCode',
                  component: () => import('@/components/org/linkButton'),
                  clickEvent: (index) => {
                    this.editRowData = this.$utils.deepCopy(this.$refs['multipleTable'].list[index])
                    this.visiblePop = true
                  }
                }
              ]
            },
            {
              prop: 'carLicense',
              label: '车牌号'
            },
            {
              prop: 'vin',
              label: 'VIN',
              width: 140
            },
            {
              prop: 'custName',
              label: '客户姓名'
            },
            {
              prop: 'outStorageType',
              label: '出库类型'
            },
            {
              prop: 'trunRepairDate',
              label: '派工日期',
              width: 140
            },
            // {
            //   prop: 'partNo',
            //   label: '备件编码',
            //   width: 140
            // },
            // {
            //   prop: 'partName',
            //   label: '备件名称'
            // },
            // {
            //   prop: 'warehouseId',
            //   label: '出库仓库',
            //   width: 140,
            //   isSlot: true
            // },
            // {
            //   prop: 'storageLocation',
            //   label: '仓位编码',
            //   width: 140
            // },
            {
              prop: 'saName',
              label: '服务顾问'
            },
            // {
            //   prop: 'partQty',
            //   label: '申请数量'
            // },
            // {
            //   prop: 'outQty',
            //   label: '已出库数量'
            // },
            // {
            //   prop: 'returnQty',
            //   label: '已退货数量'
            // },
            // {
            //   prop: 'outStoreQty',
            //   label: '出库数量',
            //   isSlot: true,
            //   width: 140
            // },
            // {
            //   prop: 'retrospectNo',
            //   label: '追溯件号',
            //   isComponent: true,
            //   comps: [
            //     {
            //       compKey: 'compKey5' + this.$utils.generateId(),
            //       codeField: 'retrospectNo',
            //       component: () => import('@/components/org/commonInput'),
            //       type: 'inputText'
            //     }
            //   ],
            //   width: 120
            // },
            // {
            //   prop: 'pickingPersonName',
            //   label: '领料人',
            //   isComponent: true,
            //   comps: [
            //     {
            //       compKey: 'compKey5' + this.$utils.generateId(),
            //       codeField: 'pickingPersonName',
            //       component: () => import('@/components/org/commonInput'),
            //       type: 'inputText'
            //     }
            //   ],
            //   width: 120
            // },
            // {
            //   prop: 'remark',
            //   label: '备注',
            //   isComponent: true,
            //   comps: [
            //     {
            //       compKey: 'compKey5' + this.$utils.generateId(),
            //       codeField: 'remark',
            //       component: () => import('@/components/org/commonInput'),
            //       type: 'inputText'
            //     }
            //   ],
            //   width: 120
            // }
          ],

      // 表单数据
      formField: this.$utils.getFormField(this, {
        repairOrderCode: '',
        carLicense: '',
        custName: '',
        beginDate: '',
        endDate: '',
        // partNo: '',
        // partName: '',
        // warehouseCode: '',
        // warehouseName: '',
        isRetrospect: '',
        warehouseId: '',
        dlrId: '',
        partId: '',
        updateControlId: ''
      }, this.$ConfigCache.CacheConfig.cacheData[viewPageCode]),

      callbackObj: {
        onCheckSelectChange: (selection) => {
          this.selectData = selection

          this.handleSelectionChange(selection)
        }
      }
    }
  },

  mounted() {
    // 列表查询
    this.queryTable(1)
    // this.loadwarehouseData()
  },

  methods: {
    // 出库数量
    outStoreQtyChange(outQty, row, col) {

    },
    valChange(val, row, col) {
      const target = row['options'].find(opt => opt.warehouseId === val)
      this.$set(row, 'warehouseInfo', target)
      this.$set(row, 'usableStockQty', target['usableStockQty'])
    },
    visChange(isOpen, row, col) {
      if (!isOpen) return
      this.loadWarehouseData(row)
    },
    loadWarehouseData(row) {
      this.$requestAPI({
        apiUrl: '/mp/e3sh/spareparts/nodestorehouse/sparePartsSoldOutService/findStorageAndWarehouse.do',
        variables: { partId: row['partId'], partNo: row['partNo'] }
      }).then(res => {
        if (res.result === '1') {
          this.$set(row, 'options', res.rows)
        } else {
          this.$message(res.msg ? res.msg : '')
        }
      }).catch(err => {
        if (err.response.data.msg) {
          this.$message(err.response.data.msg)
        } else {
          this.$message(err.message)
        }
      })
    },
    // 出库
    delivery() {
      let isValid = true
      this.selectData.every(row => {
        if (!('warehouseInfo' in row)) {
          isValid = false
          return false
        }
        return true
      })
      if (!isValid) return this.$message('表格中 [ 出库仓库 ] 为必选项 !')
      this.$confirm('确定要出库吗?', '提示', {
        type: 'warning'
      }).then(() => {
        const queryObj = {
        // 保存需要传 type="mutation"
          type: 'mutation',
          apiConfig: {
            APIUrl: '/mp/e3sh/spareparts/nodestorehouse/repairOutStorageService/outStorage.do'
          },
          // 条件/实体参数（变量），根据typeParam中的定义配置

          variables: {
            dataInfo: this.selectData
          }
        }
        // 转换了中台请求格式数据
        var paramD = this.$getParams(queryObj)
        this.$requestAPI(paramD).then((response) => {
          if (response.result === '1') {
            this.$message({
              message: response.msg
            })
          } else {
            this.$message({
              message: response.msg
            })
          }
          this.queryTable(1)
        })
      })
    },

    // 当选择项发生变化时会触发该事件
    handleSelectionChange(selection) {
      const btns = this.tableButtons.filter(o => o.disabled !== undefined)
      if (btns.length > 0) {
        const isCheck = selection && selection.length > 0
        btns.forEach((item) => {
          item.disabled = !isCheck
        })
      }
    }
  }
}
</script>
